#include "FileLog.h"
#include<fcntl.h>
#include<iostream>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/types.h>
bool tmms::base::FileLog::Open(const std::string &filepath)
{
    file_path_ = filepath;
    int fd = ::open(file_path_.c_str(),O_CREAT|O_APPEND|O_WRONLY,DEFFILEMODE);
    if(fd<0){
        std::cout<<"open file log error path:"<<file_path_<<std::endl;
        return false;
    }
    fd_ = fd;
    return true;
}

size_t tmms::base::FileLog::WriteLog(const std::string &msg)
{
    int fd = fd_==-1?1:fd_;
    return write(fd,msg.data(),msg.size());
}

void tmms::base::FileLog::Rotate(const std::string &file)
{
    if(file_path_.empty()){
        return;
    }
    int ret = ::rename(file_path_.c_str(),file.c_str());
    if(ret!=0){
        std::cerr<<"rename filed old:"<<file_path_<<" new:"<<file<<std::endl;
    }
    int fd = ::open(file_path_.c_str(),O_CREAT|O_APPEND|O_WRONLY,DEFFILEMODE);
    if(fd<0){
        std::cout<<"open file log error path:"<<file<<std::endl;
        return;
    }
    ::dup2(fd,fd_);
    close(fd);
}

tmms::base::RotateType tmms::base::FileLog::GetRotateType() const
{
    return Rotate_type_; 
}

void tmms::base::FileLog::SetRotate(RotateType type)
{
    Rotate_type_ = type;
}

int64_t tmms::base::FileLog::FileSize() const
{
    return lseek64(fd_,0,SEEK_END);
}

std::string tmms::base::FileLog::FilePath() const
{
    return file_path_;
}
